package com.fengwk.support.util;

import java.io.Serializable;
import java.util.List;

import com.fengwk.support.exception.BaseException;
import com.github.pagehelper.PageHelper;

/**
 * 分页工具,目前采用pagehelper
 * 
 * @author fengwk
 * @version 创建时间:2017年6月25日 下午9:26:16
 */
public class PageUtils {
	
	private PageUtils() {
		throw new BaseException("can not instance " + getClass());
	}

	public static void startPage(Integer pageNum, Integer pageSize) {
		if(pageNum == null || pageSize == null) {
			return;
		}
		PageHelper.startPage(pageNum, pageSize);
	}
	
	public static void orderBy(String sortName, String sortOrder) {
		Sort _sort = new Sort();
		_sort.setSortName(sortName);
		_sort.setSortOrder(sortOrder);
		orderBy(_sort);
	}
	
	public static void orderBy(String orderBy) {
		if(StringUtils.isBlank(orderBy)) {
			return;
		}
		PageHelper.orderBy(orderBy);
	}
	
	public static void orderBy(Sort sort) {
		String orderBy = sort.getOrderBy();
		orderBy(orderBy);
	}
	
	public static void orderBy(List<Sort> sortList) {
		if(CollectionUtils.isBlank(sortList)) {
			return;
		}
		StringBuffer sb = new StringBuffer();
		for(Sort _sort: sortList) {
			String _orderBy = _sort.getOrderBy();
			if(StringUtils.isBlank(_orderBy)) {
				continue;
			}
			sb.append(_orderBy + ",");
		}
		int len = sb.length();
		if(len <= 0) {
			return;
		}
		orderBy(sb.substring(0, len - 1));
	}
	
	/**
	 * 分页模型
	 * @author fengwk
	 * @version 创建时间:2017年6月25日 下午9:45:09
	 */
	public static class Sort implements Serializable {
		
		private static final long serialVersionUID = 4384540836548963107L;
		
		private String sortName;
		private String sortOrder;
		
		public static final String ASC_ORDER = "asc";
		public static final String DESC_ORDER = "desc";
		
		public String getOrderBy() {
			if(StringUtils.isBlank(sortName)) {
				return null;
			}
			String _sortOrder = null;
			if(ASC_ORDER.equalsIgnoreCase(sortOrder)) {
				_sortOrder = ASC_ORDER;
			}
			if(DESC_ORDER.equalsIgnoreCase(sortOrder)) {
				_sortOrder = DESC_ORDER;
			}
			return sortName + (StringUtils.isBlank(_sortOrder) ? "" : " " + _sortOrder);
		}
		
		public String getSortName() {
			return sortName;
		}

		public void setSortName(String sortName) {
			this.sortName = sortName;
		}

		public String getSortOrder() {
			return sortOrder;
		}

		public void setSortOrder(String sortOrder) {
			this.sortOrder = sortOrder;
		}

	}

}
